﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Virgee.Common.Interfaces;

namespace Virgee.Common.Serializers
{
    public class JsonSerializer : ISerializer
    {
        /// <summary>
        /// The default json serializer.
        /// </summary>
        protected System.Web.Script.Serialization.JavaScriptSerializer Serializer = new System.Web.Script.Serialization.JavaScriptSerializer();

        /// <summary>
        /// A Json serializer that wraps <see cref="T:System.Web.Script.Serialization.JavaScriptSerializer"/>
        /// </summary>    
        public JsonSerializer()
        {
            // This space intentionally left blank
        }

        /// <summary>
        /// Serializes the given input object to json format.
        /// </summary>
        /// <typeparam name="T">The input type.</typeparam>
        /// <param name="input">The input value.</param>
        /// <param name="additionalInfo">Used to pass additional information that may be required by the serializer to serialize the input object.</param>
        /// <returns>Returns a <see cref="T:System.String"/> instance in json format representing the serialized object.</returns>
        public virtual string Serialize<T>(T input, IDictionary<string, object> additionalInfo = null) where T : class
        {
            Is.NotNull(input, "input");

            return Serializer.Serialize(input);
        }

        /// <summary>
        /// Deserializes the given <see cref="T:System.String"/> in json format to an instance of an object of the specified type.
        /// </summary>
        /// <typeparam name="T">The type.</typeparam>
        /// <param name="input">The json <see cref="T:System.String"/> input.</param>
        /// <param name="additionalInfo">Used to pass additional information that may be required by the serializer to deserialize the input <see cref="T:System.String"/>.</param>
        /// <returns>Returns an instance of the specified type deserialized from the given <see cref="T:System.String"/> in json format.</returns>
        public virtual T Deserialize<T>(string input, IDictionary<string, object> additionalInfo = null) where T : class
        {
            Is.NotNull(input, "input");
            
            return (T)Serializer.Deserialize(input, typeof(T));
        }

        /// <summary>
        /// Returns Json media type.
        /// </summary>
        public virtual string MediaType
        {
            get { return "application/json"; }
        }
    }
}
